package com.cskaoyan.config;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.LinkedHashMap;

@Configuration
public class ShiroConfiguration {
    //shiroFilter
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/admin/auth/login");//认证失败的url
        LinkedHashMap<String, String> fileterChainDefinitionMap = new LinkedHashMap<>();
        //该请求对应anon filter  匿名filter
        fileterChainDefinitionMap.put("/admin/auth/login","anon");
        fileterChainDefinitionMap.put("/wx/auth/login","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(fileterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }


    // securityManager
    @Bean
    public DefaultWebSecurityManager securityManager(AdminRealm adminRealm,WxCustormRealm wxCustormRealm,
                                                     CustomShiroSessionManager customShiroSessionManager,
                                                     CustomAuthenticator customAuthenticator){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //
        //defaultWebSecurityManager.setRealm(adminRealm);
        defaultWebSecurityManager.setSessionManager(customShiroSessionManager);
        defaultWebSecurityManager.setAuthenticator(customAuthenticator);
        return defaultWebSecurityManager;
    }

    //Realm---默认的不好用--提供自定义的relm----主要开发的内容
    //需要实现接口
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean
    public CustomAuthenticator authenticator(AdminRealm adminRealm,WxCustormRealm wxCustormRealm){

        CustomAuthenticator customAuthenticator = new CustomAuthenticator();
        ArrayList<Realm> realms = new ArrayList<>();
        realms.add(adminRealm);
        realms.add(wxCustormRealm);
        customAuthenticator.setRealms(realms);
        return customAuthenticator;
    }

}
